package com.compass.doctor.dialog

import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.compass.doctor.databinding.DialogConsumableCodeBinding
import com.compass.framework.R
import com.compass.framework.base.BaseDialog
import com.compass.framework.base.BaseDialogFragment
import com.compass.framework.ext.dp2px
import com.compass.framework.ext.onClick
import com.compass.framework.glide.setUrl
import com.compass.framework.glide.setUrlAsBitmap
import com.compass.framework.manager.AppManager
import com.google.zxing.BarcodeFormat
import com.google.zxing.MultiFormatWriter
import com.google.zxing.WriterException
import com.google.zxing.common.BitMatrix
import com.journeyapps.barcodescanner.BarcodeEncoder


/**
 * Description：耗材订单二维码
 * Date:2024/1/11 11:23
 */
class CompleteOrderCodeDialog {
    class Builder(activity: FragmentActivity, private var wxCode: String?) :
        BaseDialogFragment.Builder<Builder>(activity) {


        private val mBinding: DialogConsumableCodeBinding =
            DialogConsumableCodeBinding.inflate(LayoutInflater.from(activity))

        init {
            initView()
        }

        private fun initView() {

            setContentView(mBinding.root)
            setWidth((AppManager.getScreenWidthPx() * 0.8).toInt())
            setHeight(ViewGroup.LayoutParams.WRAP_CONTENT)
            setAnimStyle(BaseDialog.AnimStyle.DEFAULT)
            setGravity(Gravity.CENTER)
            setCancelable(false)

            wxCode?.let {
                mBinding.imgWxCode.setBackgroundDrawable(BitmapDrawable(encodeAsBitmap(it)))
            }

            mBinding.tvCancel.onClick {
                dismiss()
            }

        }


        private fun encodeAsBitmap(str: String): Bitmap? {
            var bitmap: Bitmap? = null
            var result: BitMatrix? = null
            val multiFormatWriter = MultiFormatWriter()
            try {
                result = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, 400, 400)
                // 使用 ZXing Android Embedded 要写的代码
                val barcodeEncoder = BarcodeEncoder()
                bitmap = barcodeEncoder.createBitmap(result)
            } catch (e: WriterException) {
                e.printStackTrace()
            } catch (iae: IllegalArgumentException) { // ?
                return null
            }

            return bitmap
        }

        public fun dismissDialog(){
            dismiss()
        }
    }
}